package manager.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

@WebListener
public class SessionListener implements HttpSessionListener, HttpSessionAttributeListener {

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext sc = session.getServletContext();
        Integer onlineNum = (Integer) sc.getAttribute("ONLINE_NUM");
        if (onlineNum==null){
            sc.setAttribute("ONLINE_NUM",1);
        }else {
            sc.setAttribute("ONLINE_NUM",onlineNum+1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext sc = session.getServletContext();
        Integer onlineNum = (Integer) sc.getAttribute("ONLINE_NUM");
        sc.setAttribute("ONLINE_NUM",onlineNum-1);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        HttpSession session = httpSessionBindingEvent.getSession();
        ServletContext sc = session.getServletContext();
        Integer onlineNum = (Integer) sc.getAttribute("ONLINE_LOGIN_NUM");
        if("login_user".equals(httpSessionBindingEvent.getName())){
            if (onlineNum==null){
                sc.setAttribute("ONLINE_LOGIN_NUM",1);
            }else {
                sc.setAttribute("ONLINE_LOGIN_NUM",onlineNum+1);
            }
        }

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}
